package cn.jetpiece.cloud.system.dp.app.modular.biz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.jetpiece.cloud.model.exception.ServiceException;
import cn.jetpiece.cloud.system.dp.app.enums.DataStatusEnum;
import cn.jetpiece.cloud.system.dp.app.modular.biz.entity.DpTApi;
import cn.jetpiece.cloud.system.dp.app.modular.biz.entity.DpTScopeData;
import cn.jetpiece.cloud.system.dp.app.modular.biz.mapper.DpTApiMapper;
import cn.jetpiece.cloud.system.dp.app.modular.biz.service.IDpTApiService;
import cn.jetpiece.cloud.system.dp.app.modular.biz.service.IDpTScopeDataService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * dp_t_api
 *
 * @author jetpiece
 * @since 2023-05-15
 */
@Service
public class DpTApiServiceImpl extends ServiceImpl<DpTApiMapper, DpTApi> implements IDpTApiService {

    @Autowired
    private IDpTScopeDataService dpTScopeDataService;

    @Override
    public DpTApi getByPath(String appKey, String servletPath) {
        DpTScopeData scopeData = dpTScopeDataService.getByAppKey(appKey);
        if (ObjectUtil.isNull(scopeData)) {
            throw new ServiceException(400, "数据权限访问缺失");
        }
        List<DpTApi> apiList = this.getByPath(servletPath);
        if (StringUtils.isNotBlank(scopeData.getApiValue())) {
            if (CollUtil.isNotEmpty(apiList)) {
                for (DpTApi api : apiList) {
                    if (scopeData.getApiValue().contains(api.getId() + ",")) {
                        return api;
                    }
                }
            }
        }
        return null;
    }

    private List<DpTApi> getByPath(String servletPath) {
        return new LambdaQueryChainWrapper<DpTApi>(this.getBaseMapper())
                .eq(DpTApi::getPath, servletPath)
                .eq(DpTApi::getDataStatus, DataStatusEnum.NORMAL.getValue())
                .list();
    }
}
